package com.chenyue.cm.account.service.impl;


import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chenyue.cm.account.dao.JdAccountRecordMapper;
import com.chenyue.cm.account.domain.JdAccount;
import com.chenyue.cm.account.domain.JdAccountRecord;
import com.chenyue.cm.account.service.JdAccountRecordService;
import com.chenyue.cm.account.vo.AccountSource;
import com.chenyue.cm.account.vo.ChangeType;
import com.chenyue.cm.account.vo.SignInfo;
import com.chenyue.cm.base.dao.LcBaseMapper;
import com.chenyue.cm.base.service.BaseServiceImpl;
import com.chenyue.cm.bean.Success;
import com.chenyue.cm.common.constant.ErrorCode;
import com.chenyue.cm.common.dao.JdGoldSignMapper;
import com.chenyue.cm.common.domain.JdGoldSign;
import com.chenyue.cm.exception.SysRuntimeException;
import com.chenyue.cm.utils.DateUtils;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.Calendar;
import java.util.Date;

/**
 * @author LBX
 */
@Service(value = "JdAccountRecordService")
public class JdAccountRecordServiceImpl extends BaseServiceImpl<JdAccountRecord> implements JdAccountRecordService {

    @Resource
    private JdAccountRecordMapper accountRecordMapper;

    private final JdGoldSignMapper goldSignMapper;

    public JdAccountRecordServiceImpl(
            @Qualifier("jdGoldSignMapper") JdGoldSignMapper goldSignMapper
    ) {
        this.goldSignMapper = goldSignMapper;
    }

    @Override
    @Resource(name = "jdAccountRecordMapper")
    public void setBaseMapper(LcBaseMapper<JdAccountRecord, Serializable> baseMapper) {
        this.baseMapper = baseMapper;
    }

    /**
     * 、
     * 金币签到
     *
     * @param id     用户id
     * @param amount 账户
     * @return 签到提示
     */
    @Override
    public Success<String> sign(Integer id, JdAccount amount) {
        JdAccountRecord accountRecord = accountRecordMapper.selectOne(
                new QueryWrapper<JdAccountRecord>().lambda()
                        .eq(JdAccountRecord::getUserId, id)
                        .eq(JdAccountRecord::getSource, AccountSource.DAILY_SIGN)
                        .last(" limit 1 ")
                        .orderByDesc(JdAccountRecord::getCt)
        );
        if (accountRecord != null) {
            if (DateUtil.isSameDay(accountRecord.getCt(), Calendar.getInstance().getTime())) {
                return Success.error("您今天已经签到");
            }
        }
//        记录签到
        final SignInfo signInfo = goldSign(id);
//        入账
        accountRecord = new JdAccountRecord();
        accountRecord.setUserId(id);
        accountRecord.setAmount(Double.valueOf(signInfo.getSignGoldCount()));
        accountRecord.setChangeType(ChangeType.INCOME);
        accountRecord.setSource(AccountSource.DAILY_SIGN);
        accountRecord.setCt(Calendar.getInstance().getTime());
        int insert = accountRecordMapper.insert(accountRecord);

        amount.setEt(Calendar.getInstance().getTime());
        amount.setAmount(amount.getAmount() + signInfo.getSignGoldCount());
        return insert > 0 ? Success.success() : Success.error();
    }

    private SignInfo goldSign(Integer userId) {
        SignInfo signInfo = new SignInfo();
        JdGoldSign goldSign = goldSignMapper.selectOne(
                new LambdaQueryWrapper<JdGoldSign>()
                        .eq(JdGoldSign::getUserId, userId)
        );
        final Date now = Calendar.getInstance().getTime();
        if (goldSign == null) {
//            第一次 新增
            goldSign = new JdGoldSign();
            goldSign.setCurrent(1);
            goldSign.setTotal(1);
            goldSign.setUserId(userId);
            goldSign.setCt(now);
            goldSignMapper.insert(goldSign);
            signInfo.setIsSign(1);
            signInfo.setSignCountTotal(1);
            signInfo.setSignCountCurrent(1);
        } else {
//            不是第一次
            if (DateUtil.offsetDay(goldSign.getCt(), 1).getTime() < now.getTime()) {
//                断签
                goldSign.setCurrent(1);
            } else {
                goldSign.setCurrent(goldSign.getCurrent() + 1);
            }
            goldSign.setTotal(goldSign.getTotal() + 1);
            goldSign.setCt(now);
            goldSignMapper.updateById(goldSign);
            signInfo.setIsSign(1);
            signInfo.setSignCountTotal(goldSign.getTotal());
            signInfo.setSignCountCurrent(goldSign.getCurrent());
        }
        return signInfo;
    }


    /**
     * 获取签到内容
     *
     * @param id userId
     * @return 签到内容
     */
    @Override
    public SignInfo getSign(Integer id) {
        final JdGoldSign sign = goldSignMapper.selectOne(
                new LambdaQueryWrapper<JdGoldSign>()
                        .eq(JdGoldSign::getUserId, id)
        );
        final SignInfo signInfo = new SignInfo();
        if (sign == null) {
            signInfo.setSignCountTotal(0);
            signInfo.setSignCountCurrent(0);
            signInfo.setIsSign(2);
        } else {
            signInfo.setSignCountTotal(sign.getTotal());
            signInfo.setSignCountCurrent(sign.getCurrent());
            signInfo.setIsSign(DateUtil.isSameDay(sign.getCt(), DateUtils.getToday()) ? 1 : 2);
        }
        return signInfo;
    }

    /**
     * 删除账户记录
     *
     * @param id 记录id
     */
    @Override
    public void delete(Integer id) {
        final int flag = accountRecordMapper.deleteById(id);
        if (flag == 0) {
            throw new SysRuntimeException(ErrorCode.DELETE_ERROR.getMsg());
        }
    }
}
